//
//  Weather proxy device
//

package main

import (
	"fmt"
	"os"
	"zmq"
)

func device(frontend, backend *zmq.Socket) os.Error {
	msg, err := zmq.InitMsg()
	if err != nil {
		return err
	}
	defer msg.Close()
	var more int64
	for {
		for {
			_, err = frontend.RecvMsg(msg, 0)
			if err != nil {
				return err
			}
			err := frontend.GetOptionVal(zmq.RCVMORE, &more)
			if err != nil {
				return err
			}
			if more == 0 {
				backend.SendMsg(msg, 0)
				break
			} else {
				backend.SendMsg(msg, zmq.SNDMORE)
			}
		}
	}
	return nil
}

func zmq_main() os.Error {
	context, err := zmq.Init(1)
	if err != nil {
		return err
	}
	defer context.Close()

	frontend, err := context.Socket(zmq.SUB)
	if err != nil {
		return err
	}
	defer frontend.Close()

	err = frontend.Connect("tcp://localhost:5556")
	if err != nil {
		return err
	}

	backend, err := context.Socket(zmq.PUB)
	if err != nil {
		return err
	}
	defer backend.Close()

	err = backend.Bind("tcp://*:8100")
	if err != nil {
		return err
	}

	err = frontend.SetOptionByte(zmq.SUBSCRIBE, nil)
	if err != nil {
		return err
	}
	return device(frontend, backend)
	//zmq.Device(zmq.QUEUE, frontend, backend)	
}

var errch = make(chan os.Error)

func main() {
	fmt.Println("Weather proxy device!")
	exit := make(chan bool)
	go func() {
		for {
			err := <-errch
			if err != nil {
				fmt.Println(err)
				os.Exit(1)
			}
		}
	}()
	go func() {
		err := zmq_main()
		if err != nil {
			errch <- err
		} else {	
			exit <- true
		}
	}()
	<-exit
}
